package com.hopes.bizz.risk.support.listener;

import com.alibaba.fastjson.JSONObject;
import com.hopes.bizz.risk.activemq.consumer.ActiveMqTopicConsumer;
import com.hopes.bizz.risk.tenant.factory.TenantConfigInitFactory;
import com.hopes.boss.admin.api.entity.SysTenant;
import com.hopes.boss.common.core.constant.ActiveMqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/8/14 9:28
 * @Description:
 */
//@Component
@Slf4j
public class TenantMessageListener implements MessageListener, CommandLineRunner {
    @Autowired
    private ActiveMqTopicConsumer activeMqTopicConsumer;
    @Autowired
    private TenantConfigInitFactory tenantConfigInitFactory;

    @Override
    public void onMessage(Message message) {
        String data = null;
        try {
            data = message.getBody(String.class);
        } catch (JMSException e) {
            log.error("消息消费失败,原因: {}", e.getMessage());
        }
        log.info("消息主体内容: {}", data);
        SysTenant tenant = JSONObject.parseObject(data, SysTenant.class);
        if (tenant != null) {
            log.info("收到新建租户信息: {}", tenant.toString());
        }
        tenantConfigInitFactory.init(tenant);
    }

    @Override
    public void run(String... args) {
        try {
            activeMqTopicConsumer.addConsumer(ActiveMqConstant.KEY_TOPIC_TENANT, this);
        } catch (Exception e) {
            log.error("消费者创建失败,原因: {}", e.getMessage());
        }
    }
}
